package com.imooc.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.mapper.SearchRecordsMapper;
import com.imooc.mapper.VideosMapper;
import com.imooc.mapper.VideosMapperCustom;
import com.imooc.pojo.SearchRecords;
import com.imooc.pojo.Videos;
import com.imooc.pojo.vo.VideosVo;
import com.imooc.utils.PageResult;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@SuppressWarnings("all")
public class VideoServiceImpl implements VideoService {
    @Autowired
    private VideosMapper videosMapper;
    @Autowired
    private VideosMapperCustom videosMapperCustom;

    @Autowired
    private SearchRecordsMapper searchRecordsMapper;

    @Autowired
    private Sid sid;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Videos saveVideos(Videos videos) {
        //实现全局唯一的id
        String id = sid.nextShort();
        videos.setId(id);
        //like_counts
        videos.setLikeCounts(0l);
        videos.setStatus(1);
        Date date = new Date();
        videos.setCreateTime(date);
        videosMapper.insert(videos);
        return videos;

    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public PageResult<VideosVo> list(Videos video,
                                     Integer isSaveRecord, Integer pageNum, Integer pageSize) {

        String videoDesc = video.getVideoDesc();
//        isSaveRecord 保存热搜词
        if (isSaveRecord != null && isSaveRecord == 1) {
            //需要保存
            SearchRecords searchRecords = new SearchRecords();
            searchRecords.setId(sid.nextShort().toString());
            searchRecords.setContent(videoDesc);
            searchRecordsMapper.insert(searchRecords);
        }

        PageHelper.startPage(pageNum, pageSize);
        List<VideosVo> videosVos = videosMapperCustom.queryAllVideos(videoDesc);
        PageInfo<VideosVo> videosVoPageInfo = new PageInfo<>(videosVos);
        PageResult<VideosVo> videosVoPageResult = new PageResult<>();
        BeanUtils.copyProperties(videosVoPageInfo, videosVoPageResult);
        return videosVoPageResult;
    }

    @Override
    public List<String> searchRecordsList() {
        List<String> recordsWords = searchRecordsMapper.getRecordsWords();
        return recordsWords;
    }
}
